
window.addEvent('domready', function() {
	//inject player;
	if(Browser.firefox3) {
		var flashname="player_all.swf";
	} else {
		var flashname="player_all.swf";
	}
	//~ player = new Swiff('flash/'+flashname+'?'+Math.floor(Math.random()*100000000000000000), {
		//~ 'container':$('flashcontainer'),
		//~ 'id': 'flash_player',
		//~ 'width': 1,
		//~ 'height': 1,
		//~ 'params': {
			//~ 'wMode': 'opaque',
			//~ 'bgcolor': '#ffffff',
			//~ 'allowScriptAccess':'always'
		//~ }});
	player = new Swiff('flash/'+flashname, {
		'container':$('flashcontainer'),
		'id': 'flash_player',
		'width': 1,
		'height': 1,
		'params': {
			'wMode': 'opaque',
			'bgcolor': '#ffffff',
			'allowScriptAccess':'always'
		}}).inject($$('body')[0]);
		
	var flash_trycounter=0;
	var reinjectflash=function(){
		if(++flash_trycounter<=6 && window.__flash__toXML===undefined) { 
			player.toElement().dispose().inject($$('body')[0]);
			window.setTimeout(reinjectflash,200);
		} else {
			s_request('get_songs');
		}
	}
	window.setTimeout(reinjectflash,300);
	//request current songlist
	
	//~ if(Browser.firefox3) {
		//~ s_request.pass('get_songs').delay(1000);
	//~ } else {
		//~ s_request('get_songs');
	//~ }
	//start installcounter
	installcountupdater();
		
	//attach events to objects
	//addCSSEvents();
});


function morphbarometer(songs,installs,left,songname,time) {
	songs=songs.toInt();installs=installs.toInt();left=left.toInt();
	$$(".sound-barometer .word-counter .songname")[0].set('text',songname);
	var breite=$$(".sound-barometer .barometer")[0].getStyle('width').toInt();
	var songspan=$$(".section .songs")[0];
	var installspan=$$(".sound-barometer .word-counter .installs")[0];
	var leftspan=$$(".sound-barometer .word-counter .left")[0];
	var barometer=$$(".sound-barometer .barometer .overlay");
	var oldsongs=songspan.get('text').toInt();
    var oldinstalls=installspan.get('text').toInt();
    var oldleft=leftspan.get('text').toInt();
	var intervall=40;
	var steps=time/intervall;
	var csongs=(songs-oldsongs);
	var cinstalls=(installs-oldinstalls);
	var cleft=(left-oldleft);
	var transition=Fx.Transitions.Quad.easeIn;
	var apply=function(t) {
		var trans_state=transition(t/steps);
		songspan.set('text', Math.floor(trans_state*csongs+oldsongs));
		installspan.set('text',Math.floor(trans_state*cinstalls+oldinstalls));
		leftspan.set('text',Math.floor(trans_state*cleft+oldleft));
		barometer.setStyle('width',Math.floor(breite*((trans_state*cinstalls+oldinstalls)/(installs+left))));
		//~ barometer.setStyle('width',100*((trans_state*cinstalls+oldinstalls)/(installs+left))+'%');
	}
	for(var t=0;t<=steps;t++) {
		window.setTimeout(apply.pass([t]),t*intervall);
	}
}

function installcountupdater() {
	s_request('installcount');
	window.setTimeout(installcountupdater, 7000); //alle 7 sekunden 
}

function playSong(hash) {
	try	{
		$$('.track[hash='+hash+']').addClass('activeSong');
		player.remote('startSong', hash);
	} catch(err) {
		if(Browser.Plugins.Flash) {
			$$('.error-message.no-browser').setStyles({'height':'auto','visibility':'visible','padding':'7px'});
			s_request('theunknownnotreproducablebaderrororccured_sadbuttrue');
		}
	}
}

function pauseCurrentSong() {
	player.remote('pauseSong');
}
function stopCurrentSong() {
	if($$('.track-list .track.activeSong').length != 0)  {
		$$('.track-list .track.activeSong').removeClass('activeSong').removeClass('paused');
		player.remote('stopSong');
	}
	//use the time to reload the songlist
	s_request('get_songs');
}
function continueCurrentSong() {
	player.remote('continueSong');
}

function s_process(data){
	if(data==null) return;
	if(typeOf(data)=='object') { result=data; } else { result=JSON.decode(data); }
	if(typeOf(result)=='object') result=[result];
	if(result==null) return;
	result.each(function(job) {
		switch(job.todo) {
			case 'updateTrackList':
				updateTrackList(job.param); break;
			case 's_request':
				s_request(job.param.todo, job.param.param?job.param.param:{}); break;
			case 'playSong':
				playSong(job.param.hash); break;
			case 'showBox':
				showBox(job.param.url); break;
			case 'showSlideshow':
				slideshow(job.param.url,job.param.object); break;
			case 'updateInstallCount':
				morphbarometer(job.param.songs, job.param.installs,job.param.left,job.param.songname,6000); break;
			case 'slideto':
				coverbuttons_slideto(job.param.slideid);break;
		}
	});
}

function coverbuttons_slideto(id) {
	coverbuttons_current=id;
	$$(".image-area").fireEvent("mouseleave");
}

function s_request(todo) {
	param=arguments[1]?arguments[1]:{};
	var jsonRequest = new Request({url: 'js/'+todo, onSuccess: s_process}).post({'param': JSON.encode(param)});
}

function slideshow(url,object) {
	if($(object).retrieve('ssslide') && url==null) { $(object).retrieve('ssslide').destroy(); return; } //destroy if url is null
	
	new Request.JSON({'url': url, onSuccess:function(images) {
		if($(object).retrieve('ssslide')) $(object).retrieve('ssslide').destroy();
		var show=new Slideshow.KenBurns(object, images,{random:true,thumbnails:false,delay:4000});
		$(object).store('ssslide',show);
		}
	}).send();
}

function showBox(url) {
	var modal = new LightFace.Request({
	  width: 480,
	  //~ height: 300,
	  fixedTop: 50,
	  maskBackground: true,
	  buttons:[{'title':'Close', 'event': function(){this.destroy();}}],
	  title: 'User Information', 
	  url: url
	});
	cbox=modal;
	// Open!
	modal.open();
}

function updateTrackList(tracks){
	$$('.track-list')[0].empty();
	
	tracks.each(function(track) {
		var etrack=new Element('div', {
			'class': 'track'+(track.hasRights<1?' norigths':''),
			'hash': track.hash
			});
		new Element('div', {
			'class': 'playButton',
			'events': {
				'click': function() {
					if(!this.getParent('.track').hasClass('activeSong')) {
						//stopoldsong
						stopCurrentSong();
						//playnewsong
						s_request('prepareSong',{'hash': this.getParent('.track').get('hash')});
					} else {
						if(this.getParent('.track').hasClass('paused')) {
							continueCurrentSong();
							this.getParent('.track').removeClass('paused');
						} else  {
							pauseCurrentSong();
							this.getParent('.track').addClass('paused');
						}
					}
				}
			}}).inject(etrack);
		new Element('div', {
			'class': 'trackName',
			'text': track.title
		}).inject(etrack);
			$$('.track-list').grab(etrack);
		});
}

function flash_trace(str) {
	//~ if(console) console.info("[flash] "+str); 
};



